import React, { memo, useCallback, useEffect, useRef, useState } from 'react'
import { LoginWrapper } from './style'
import initCanvas from '@/utils/login_canvas'
import { Button, Checkbox, Col, Form, Input, Row, message } from 'antd'
import {
  LockOutlined,
  UserOutlined,
  HighlightOutlined
} from '@ant-design/icons'
import {
  userRegister,
  userLogin,
  getUserSecret,
  verifySecret
} from '@/network/blog/user.request'
import { changeBlogUserAction } from '@/store/blog/actionCreators'
import { useDispatch } from 'react-redux'
import eventBus from '@/utils/eventBus'
import Captcha from 'react-captcha-code'
import setMessage from '@/utils/setMessage'

export default memo(function B_Login(props) {
  const [isRegister, setIsRegister] = useState(false)
  const [isForget, setIsForget] = useState(false)
  const [nickname, setNickname] = useState('')
  const [password, setPassword] = useState('')
  const [secretText, setSecretText] = useState('这在里输入密保问题的答案')
  const [secretAnswer, setSecretAnswer] = useState('')
  const [secretId, setSecretId] = useState()
  const [userId, setUserId] = useState()
  const [code, setCode] = useState('')
  const [captcha, setCaptcha] = useState([])

  const canvasRef = useRef()
  const captchaRef = useRef()
  const dispatch = useDispatch()

  useEffect(() => {
    canvasRef.current && initCanvas(canvasRef.current)
    document.title = '登录'
  }, [])

  // 登录
  const onFinish = useCallback(async () => {
    const key = 'login-key'
    if (
      nickname.length >= 1 &&
      nickname.length <= 10 &&
      password.length >= 5 &&
      password.length <= 20
    ) {
      message.loading({ content: '正在登录...', key })
      const user = await userLogin(nickname, password)
      if (user) {
        message.destroy(key)
        localStorage.setItem('user', JSON.stringify(user))
        props.history.push(`/blog/home/u/${user.id}`)
        dispatch(changeBlogUserAction(user))
        eventBus.emit('entry', user.id)
      } else {
        message.error({ content: '用户名/密码不正确的说~', key, duration: 2 })
      }
    }
  }, [nickname, password, dispatch, props.history])

  // 注册
  const onRegister = useCallback(async () => {
    if (code === captcha) {
      const key = 'register-key'
      if (
        nickname.length >= 1 &&
        nickname.length <= 10 &&
        password.length >= 5 &&
        password.length <= 20
      ) {
        message.loading({ content: '正在注册...', key })
        const result = await userRegister(nickname, password)
        if (result && result['affectedRows'] === 1) {
          message.success({ content: '注册成功', key, duration: 2 })
        } else {
          message.warning({ content: '用户名重复啦~', key, duration: 2 })
        }
      } else {
        setMessage('输入不规范', 'info')
      }
    } else {
      code.length > 0 && setMessage('验证码错误', 'info')
      code.length > 0 && captchaRef.current.refresh()
    }
  }, [nickname, password, code, captcha])

  // 切换注册
  const toggleRegister = useCallback((flag) => {
    setIsRegister(flag)
    setNickname('')
    setPassword('')
  }, [])

  // 获取密保
  const getSecret = useCallback(async () => {
    const key = 'secret-key'
    if (nickname && nickname.length >= 0 && nickname.length < 10) {
      const [result] = await getUserSecret(nickname)
      if (result && result.question) {
        setSecretText(result.question)
        setSecretId(result.id)
        setUserId(result.userId)
      } else {
        setSecretText('未设置密保')
        message.error({ content: '未设置密保', key, duration: 2 })
      }
    }
  }, [nickname])

  // 提交答案
  const postSecret = useCallback(async () => {
    const key = 'secret-key'
    if (
      secretId &&
      secretAnswer &&
      password &&
      password.length >= 4 &&
      password.length <= 20
    ) {
      message.loading({ content: '正在验证...', key })
      const result = await verifySecret(
        secretId,
        secretAnswer,
        password,
        userId
      )
      if (result && result.code === 200) {
        message.success({
          content: '验证通过, 密码修改成功!',
          key,
          duration: 2
        })
      } else {
        message.error({ content: '答案不正确~', key, duration: 2 })
      }
    }
  }, [secretAnswer, secretId, userId, password])

  const renderLogin = () => {
    return (
      <Form
        name="normal_login"
        className="form"
        layout="horizontal"
        initialValues={{ remember: true }}
        onFinish={onFinish}
      >
        <Input
          size="large"
          className="mb-3"
          prefix={<UserOutlined className="site-form-item-icon" />}
          placeholder="用户名"
          value={nickname}
          onChange={(e) => setNickname(e.target.value)}
        />
        <Input
          size="large"
          className="mt-3 mb-2"
          prefix={<LockOutlined className="site-form-item-icon" />}
          type="password"
          value={password}
          placeholder="密码"
          onChange={(e) => setPassword(e.target.value)}
        />
        <Form.Item>
          <Form.Item name="remember" valuePropName="checked" noStyle>
            <Checkbox>记住我</Checkbox>
          </Form.Item>

          <span
            onClick={(e) => setIsForget(true)}
            className="login-form-forgot ml-4 color-white pointer"
          >
            忘记密码？
          </span>
        </Form.Item>
        <Form.Item>
          <Button
            size="large"
            type="primary"
            htmlType="submit"
            className="login-form-button mr-2"
          >
            登录
          </Button>
          <Button
            size="large"
            type="primary"
            onClick={(e) => toggleRegister(true)}
            className="register-form-button ml-2"
          >
            去注册
          </Button>
        </Form.Item>
      </Form>
    )
  }
  const renderRegister = () => {
    return (
      <Form
        name="normal_login"
        className="form"
        layout="horizontal"
        onFinish={onRegister}
      >
        <Input
          size="large"
          className="mb-3"
          prefix={<UserOutlined className="site-form-item-icon" />}
          placeholder="输入用户名 [1-10]"
          value={nickname}
          onChange={(e) => setNickname(e.target.value)}
        />
        <Input
          size="large"
          className="mt-3 mb-6"
          prefix={<LockOutlined className="site-form-item-icon" />}
          type="password"
          value={password}
          placeholder="输入密码 [5-20]"
          onChange={(e) => setPassword(e.target.value)}
        />

        <div>
          <Input
            size="large"
            className="mb-2"
            prefix={<HighlightOutlined className="site-form-item-icon" />}
            value={code}
            placeholder="输入验证码"
            onChange={(e) => setCode(e.target.value)}
          />
          <Captcha
            ref={captchaRef}
            charNum={6}
            onChange={(value) => setCaptcha(value)}
          />
        </div>

        <Form.Item>
          <Button
            size="large"
            type="primary"
            className="login-form-button mr-2"
            onClick={(e) => toggleRegister(false)}
          >
            返回
          </Button>
          <Button
            size="large"
            type="primary"
            htmlType="submit"
            className="register-form-button ml-2"
          >
            注册
          </Button>
        </Form.Item>
      </Form>
    )
  }
  const renderForget = () => {
    return (
      <Form name="normal_login" className="form" layout="horizontal">
        <Input
          size="large"
          className="mb-3"
          onChange={(e) => setNickname(e.target.value)}
          prefix={<UserOutlined className="site-form-item-icon" />}
          placeholder="输入用户名"
        />
        <Input
          size="large"
          className="mt-3 mb-5"
          value={secretAnswer}
          onChange={(e) => setSecretAnswer(e.target.value)}
          prefix={<UserOutlined className="site-form-item-icon" />}
          placeholder={secretText}
        />
        <Input
          size="large"
          className="mt-3 mb-6"
          prefix={<LockOutlined className="site-form-item-icon" />}
          type="password"
          value={password}
          placeholder="输入新密码~"
          onChange={(e) => setPassword(e.target.value)}
        />
        <Form.Item>
          <Button
            size="middle"
            type="primary"
            onClick={(e) => setIsForget(false)}
            className="register-form-button ml-2"
          >
            返回
          </Button>
          <Button
            size="middle"
            type="primary"
            onClick={(e) => getSecret()}
            className="register-form-button ml-2"
          >
            获取密保
          </Button>
          <Button
            size="middle"
            type="primary"
            onClick={(e) => postSecret()}
            className="register-form-button ml-2"
          >
            提交答案
          </Button>
        </Form.Item>
      </Form>
    )
  }

  return (
    <LoginWrapper>
      <div className="bg-canvas">
        <div className="landscape"></div>
        <div className="filter"></div>
        <canvas id="canvas" ref={canvasRef}></canvas>
      </div>
      <div className="login-form">
        <Row>
          <Col
            lg={{ span: 12, offset: 6 }}
            md={{ span: 16, offset: 4 }}
            sm={{ span: 20, offset: 2 }}
            xs={{ span: 24 }}
          >
            {isForget
              ? renderForget()
              : isRegister
              ? renderRegister()
              : renderLogin()}
          </Col>
        </Row>
      </div>
    </LoginWrapper>
  )
})
